package server

import (
	"sanguo/cluster"
	"sanguo/node/node_dir"
	ss_meg "sanguo/protocol/ss/message"
	"sync"

	"github.com/golang/protobuf/proto"
	"github.com/sniperHW/kendynet"
)

var lockMap sync.Mutex

type Server struct {
	ServerId     int32
	ServerName   string
	ServerAddr   string
	ServerStatus int //1运行中 0维护中
	playerNum    int32
}

var serverMap map[int]*Server

func GetServerMapSize() int {
	return len(serverMap)
}

func onReportStatus(session kendynet.StreamSession, msg proto.Message) {
	defer lockMap.Unlock()
	lockMap.Lock()

	reportStatus := msg.(*ss_meg.ReportStatus)

	serverId := reportStatus.GetServerId()
	serverAddr := reportStatus.GetServerAddr()
	playerNum := reportStatus.GetPlayerNum()

	//node_dir.Infoln("onReportStatus:", serverId, serverAddr, playerNum)

	s := serverMap[int(serverId)]
	if s != nil {
		for _, v := range serverMap {
			if s.ServerAddr == v.ServerAddr {
				v.ServerStatus = 1
				v.playerNum = playerNum
			}
		}
		if s.ServerAddr != serverAddr {
			node_dir.Infof("serverId %d Check address inconsistencies: %s %s\n", serverId, s.ServerAddr, serverAddr)
		}

	} else {
		node_dir.Infof("serverMap losed serverId ==> %d \n", serverId)
	}

}

func onUserLog(session kendynet.StreamSession, msg proto.Message) {
	userLog := msg.(*ss_meg.UserLog)

	userId := userLog.GetUserId()
	serverId := int(userLog.GetServerId())
	pLevel := int(userLog.GetPLevel())
	lastTime := userLog.GetLastTime()

	node_dir.Infoln("onUserLog:", userId, serverId, pLevel, lastTime)

	//更新最近登录 和 登录过的服
	updateLastLogin(userId, serverId)
	logged(userId, serverId, pLevel)

}

func init() {
	serverMap = map[int]*Server{}
	cluster.Register(&ss_meg.ReportStatus{}, onReportStatus)
	cluster.Register(&ss_meg.UserLog{}, onUserLog)
}
